import { message } from 'antd';
import { getCards } from '../../services/financial';

const defPage = {
    page: 1,
    pageSize: 10,
};
const defQuery = {
    userName: '',
    from: '',
    to: '',
};

export default {
    namespace: 'cards',
    state: {
        data: [],
        pagination: { ...defPage },
        query: { ...defQuery },
    },
    subscriptions: {
        setup(args) {
            const { dispatch, history } = args;
            history.listen(({ pathname }) => {
                if (pathname === '/financial/cards') {
                    dispatch({
                        type: 'init',
                    });
                }
            });
        }
    },
    effects: {
        * init(payload, { put, select }) {
            const { storeId } = yield select(({ app }) => app.user);
            yield put({
                type: 'upState',
                payload: { storeId, query: { ...defQuery } },
            });
            yield put({
                type: 'load',
            });
        },
        * load({ payload }, { put, select, call }) {
            const {
                query,
                pagination: { page, pageSize } = {},
                storeId,
            } = yield select(
                ({ cards }) => cards
            );
            if (!storeId) {
                message.warning('您还没有开店!');
                return;
            }
            const {
                data: {
                    list: data,
                    pageination: pagination,
                },
                code,
            } = yield call(
                getCards,
                { page, pageSize, storeId, ...query, ...payload },
            );
            if (code === '0000') {
                yield put({
                    type: 'upState',
                    payload: {
                        data,
                        pagination,
                    },
                });
            } else {
                message.error('请求失败');
            }
        },
        * reSearch({ query }, { put }) {
            yield put({
                type: 'upState',
                payload: { query },
            });
            yield put({
                type: 'load',
                payload: { ...defPage },
            });
        },
    },
    reducers: {
        upState(state, { payload }) {
            return {
                ...state,
                ...payload,
            };
        },
    }
};

